package com.pkk.penguin.frame.know.boot.schedule.zhiyi;

import static com.pkk.penguin.frame.know.boot.config.handle.zhiyi.synch.ZySynchContent.AUTH_USER_SET;
import static com.pkk.penguin.frame.know.boot.config.handle.zhiyi.synch.ZySynchContent.USER_AUTH_INFO;

import com.pkk.penguin.frame.know.boot.apis.zhiyi.SynchApi;
import com.pkk.penguin.frame.know.boot.bo.hbsl.MessageType;
import com.pkk.penguin.frame.know.boot.config.common.handle.AbstractWebSocketServer.WebScoketUtil;
import com.pkk.penguin.frame.know.boot.config.handle.zhiyi.synch.ZySynchWebSocketServer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @description: 之易定时任务
 * @author: peikunkun
 * @create: 2020-05-20 19:15
 **/
@Slf4j
@Component
public class ZhiyiSchedule {

  @Resource
  private ZySynchWebSocketServer zySynchWebSocketServer;


  /**
   * @Description: 授权会话操作
   * @Param:
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/5/20 0020 下午 8:16
   */
  @Scheduled(cron = "0 0/5 * * * ?")
  public void keepSession() {
    StringBuffer onlineLogByZhiyi = new StringBuffer();
    AtomicBoolean isLog = new AtomicBoolean(false);

    AUTH_USER_SET.stream().forEach(p -> {
      onlineLogByZhiyi.append("[").append(p).append("]").append("平台[");
      //用户平台授权信息
      final ConcurrentHashMap<String, SynchApi> authInfo = USER_AUTH_INFO.get(p);
      authInfo.keySet().stream().forEach(platformKey -> {
        final SynchApi synchApi = authInfo.get(platformKey);
        final boolean b = synchApi.keepSession();

        if (!b) {
          isLog.set(true);
          try {
            //重新授权
            authInfo.put(platformKey, synchApi.login());
            onlineLogByZhiyi.append(platformKey);
          } catch (Exception e) {
            onlineLogByZhiyi.append("-同步异常:" + e.getMessage());
          }
          onlineLogByZhiyi.append(" | ");
        }
        log.info("【授权保持会话】-[{}]-[{}]->[{}]", p, platformKey, b);
      });
      onlineLogByZhiyi.append("]会话超时,重新建立连接操作\n\n");
    });

    if (isLog.get()) {
      WebScoketUtil.broadcost(zySynchWebSocketServer.getWebSocket(), MessageType.ONLINE, onlineLogByZhiyi.toString());
    }
  }


}
